package mp

import (
	"context"
	"errors"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserSaveLogic {
	return &UserSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserSaveLogic) UserSave(req *types.UserReq) (resp string, err error) {
	data := &models.User{
		Username: req.Username,
	}
	has := db.GetData(data)
	if has && data.Id != req.Id {
		return "", errors.New("用户名已存在")
	}
	copier.Copy(data, req)

	dept := &models.Dept{
		Id: req.DeptId,
	}
	has = db.GetData(dept)
	if !has {
		return "", errors.New("选择的部门不存在")
	}
	data.DeptTier = dept.Tier + "," + utils.IntToString(dept.Id) + ","

	if req.Id == 0 {
		if data.Password == "" {
			return "", errors.New("登录密码不能为空")
		}
		data.Salt = utils.RandStr(6)
		data.Password = utils.MD5(utils.MD5(req.Password) + data.Salt)
		db.InsertData(data)
	} else {
		if req.Password != "" {
			data.Salt = utils.RandStr(6)
			data.Password = utils.MD5(utils.MD5(req.Password) + data.Salt)
		}
		db.UpdateData(data, xb.Eq{"id": req.Id})
	}

	return "操作成功", nil
}
